<template>
  <a-modal
    :title="title"
    :width="1000"
    :visible="visible"
    :footer="null"
    @cancel="handleCancel">
    
    <a-spin :spinning="loading">
      <!-- 统计概览 -->
      <a-row :gutter="16" style="margin-bottom: 24px;">
        <a-col :span="6">
          <a-card size="small">
            <a-statistic
              title="总库存数量"
              :value="overview.totalQuantity || 0"
              suffix="件"
              :value-style="{ color: '#1890ff' }"
            />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card size="small">
            <a-statistic
              title="可用数量"
              :value="overview.availableQuantity || 0"
              suffix="件"
              :value-style="{ color: '#52c41a' }"
            />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card size="small">
            <a-statistic
              title="预留数量"
              :value="overview.reservedQuantity || 0"
              suffix="件"
              :value-style="{ color: '#faad14' }"
            />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card size="small">
            <a-statistic
              title="库存总金额"
              :value="overview.totalAmount || 0"
              suffix="元"
              :precision="2"
              :value-style="{ color: '#f5222d' }"
            />
          </a-card>
        </a-col>
      </a-row>

      <!-- 统计维度选择 -->
      <a-tabs v-model="activeTab" @change="handleTabChange">
        <a-tab-pane key="warehouse" tab="按仓库统计">
          <a-table
            :columns="statisticsColumns"
            :dataSource="warehouseStatistics"
            :pagination="false"
            size="small"
            :scroll="{y: 300}">
            
            <template slot="progress" slot-scope="text, record">
              <div>
                <div style="margin-bottom: 4px;">
                  <span style="color: #52c41a;">可用: {{ record.availableQuantity }}</span>
                  <span style="color: #faad14; margin-left: 16px;">预留: {{ record.reservedQuantity }}</span>
                </div>
                <a-progress 
                  :percent="getUtilizationRate(record)" 
                  size="small" 
                  :stroke-color="getProgressColor(record)"
                  :show-info="false"/>
              </div>
            </template>
          </a-table>
        </a-tab-pane>

        <a-tab-pane key="order" tab="按订单统计">
          <a-table
            :columns="orderStatisticsColumns"
            :dataSource="orderStatistics"
            :pagination="{ pageSize: 10 }"
            size="small">
            
            <template slot="progress" slot-scope="text, record">
              <div>
                <div style="margin-bottom: 4px;">
                  <span style="color: #52c41a;">可用: {{ record.availableQuantity }}</span>
                  <span style="color: #faad14; margin-left: 16px;">预留: {{ record.reservedQuantity }}</span>
                </div>
                <a-progress 
                  :percent="getUtilizationRate(record)" 
                  size="small" 
                  :stroke-color="getProgressColor(record)"
                  :show-info="false"/>
              </div>
            </template>
          </a-table>
        </a-tab-pane>

        <a-tab-pane key="windowSeries" tab="按门窗系列统计">
          <a-table
            :columns="statisticsColumns"
            :dataSource="windowSeriesStatistics"
            :pagination="false"
            size="small"
            :scroll="{y: 300}">
            
            <template slot="progress" slot-scope="text, record">
              <div>
                <div style="margin-bottom: 4px;">
                  <span style="color: #52c41a;">可用: {{ record.availableQuantity }}</span>
                  <span style="color: #faad14; margin-left: 16px;">预留: {{ record.reservedQuantity }}</span>
                </div>
                <a-progress 
                  :percent="getUtilizationRate(record)" 
                  size="small" 
                  :stroke-color="getProgressColor(record)"
                  :show-info="false"/>
              </div>
            </template>
          </a-table>
        </a-tab-pane>
      </a-tabs>

      <!-- 操作按钮 -->
      <div style="text-align: right; margin-top: 16px;">
        <a-button @click="exportStatistics" type="primary" icon="download">导出统计</a-button>
        <a-button @click="refreshStatistics" style="margin-left: 8px;" icon="reload">刷新</a-button>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import { getAction } from '@/api/manage'

export default {
  name: 'InventoryStatisticsModal',
  data() {
    return {
      title: "库存统计分析",
      visible: false,
      loading: false,
      activeTab: 'warehouse',
      overview: {},
      warehouseStatistics: [],
      orderStatistics: [],
      windowSeriesStatistics: [],
      statisticsColumns: [
        {
          title: '名称',
          dataIndex: 'dimensionValue',
          width: 150,
        },
        {
          title: '总数量',
          dataIndex: 'totalQuantity',
          width: 80,
          sorter: (a, b) => a.totalQuantity - b.totalQuantity,
        },
        {
          title: '库存分布',
          dataIndex: 'progress',
          width: 200,
          scopedSlots: { customRender: 'progress' }
        },
        {
          title: '总金额',
          dataIndex: 'totalAmount',
          width: 100,
          customRender: (text) => text ? `¥${text.toFixed(2)}` : '¥0.00',
          sorter: (a, b) => (a.totalAmount || 0) - (b.totalAmount || 0),
        },
        {
          title: '订单数',
          dataIndex: 'orderCount',
          width: 80,
          sorter: (a, b) => a.orderCount - b.orderCount,
        },
        {
          title: '库位数',
          dataIndex: 'locationCount',
          width: 80,
          sorter: (a, b) => a.locationCount - b.locationCount,
        }
      ],
      orderStatisticsColumns: [
        {
          title: '订单号',
          dataIndex: 'dimensionValue',
          width: 150,
        },
        {
          title: '总数量',
          dataIndex: 'totalQuantity',
          width: 80,
          sorter: (a, b) => a.totalQuantity - b.totalQuantity,
        },
        {
          title: '库存分布',
          dataIndex: 'progress',
          width: 200,
          scopedSlots: { customRender: 'progress' }
        },
        {
          title: '总金额',
          dataIndex: 'totalAmount',
          width: 100,
          customRender: (text) => text ? `¥${text.toFixed(2)}` : '¥0.00',
          sorter: (a, b) => (a.totalAmount || 0) - (b.totalAmount || 0),
        },
        {
          title: '库位数',
          dataIndex: 'locationCount',
          width: 80,
          sorter: (a, b) => a.locationCount - b.locationCount,
        }
      ]
    }
  },
  methods: {
    show() {
      this.visible = true;
      this.loadStatistics();
    },
    async loadStatistics() {
      this.loading = true;
      try {
        // 并行加载所有统计数据
        const [overviewRes, warehouseRes, orderRes, windowSeriesRes] = await Promise.all([
          getAction('/wms/finished-goods/inventory/statistics/overview'),
          getAction('/wms/finished-goods/inventory/statistics/warehouse'),
          getAction('/wms/finished-goods/inventory/statistics/order'),
          getAction('/wms/finished-goods/inventory/statistics/window-series')
        ]);

        if (overviewRes.success) {
          this.overview = overviewRes.result || {};
        }
        if (warehouseRes.success) {
          this.warehouseStatistics = warehouseRes.result || [];
        }
        if (orderRes.success) {
          this.orderStatistics = orderRes.result || [];
        }
        if (windowSeriesRes.success) {
          this.windowSeriesStatistics = windowSeriesRes.result || [];
        }
      } catch (error) {
        this.$message.error('加载统计数据失败');
        console.error('加载统计数据失败', error);
      } finally {
        this.loading = false;
      }
    },
    handleTabChange(key) {
      this.activeTab = key;
    },
    getUtilizationRate(record) {
      if (!record.totalQuantity) return 0;
      return Math.round((record.availableQuantity / record.totalQuantity) * 100);
    },
    getProgressColor(record) {
      const rate = this.getUtilizationRate(record);
      if (rate >= 80) return '#52c41a';
      if (rate >= 50) return '#faad14';
      return '#f5222d';
    },
    refreshStatistics() {
      this.loadStatistics();
    },
    exportStatistics() {
      this.$message.info('导出功能开发中...');
      // TODO: 实现导出功能
    },
    handleCancel() {
      this.close();
    },
    close() {
      this.visible = false;
      this.activeTab = 'warehouse';
      this.overview = {};
      this.warehouseStatistics = [];
      this.orderStatistics = [];
      this.windowSeriesStatistics = [];
    }
  }
}
</script>

<style scoped>
.ant-statistic-content {
  font-size: 20px;
}
</style>
